package com.zmx.job.admin.service;

import com.zmx.core.dto.RequestDataInfo;
import com.zmx.core.dto.RequestLogInfo;
import com.zmx.core.dto.ReturnT;
import com.zmx.core.utils.AESUtil;
import com.zmx.core.utils.JacksonUtil;
import com.zmx.core.utils.JobRemotingUtil;
import com.zmx.job.admin.core.conf.MallAdminConfig;
import com.zmx.job.admin.core.nodedistribute.JobRouteStrategyInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Description: 实时取各个实例日志服务类
 * @ClassName: LogInfoService
 * @Author zhaomxr
 * @Date 2021-12-24 13:56
 */
@Slf4j
@Service
public class LogInfoService {

    @Autowired
    private MallAdminConfig mallAdminConfig;

    public RequestLogInfo getLog(String name, String pointer) {
        if (StringUtils.isEmpty(name)) {
            throw new RuntimeException("name is empty");
        }

        try {

            String node = JobRouteStrategyInfo.getJobInstance(name);
            if (StringUtils.isEmpty(node)) {
                log.error("没有找到任务[{}]所在节点", node);
                return null;
            }

            String url = mallAdminConfig.getRequestUrlPrefix() + node;

            RequestDataInfo requestDataInfo = new RequestDataInfo();
            String aseContent = mallAdminConfig.getUsername() + mallAdminConfig.getPassword();
            String aesSecret = mallAdminConfig.getSecret();
            requestDataInfo.setVerification(AESUtil.aesEncrypt(aseContent, aesSecret));
            requestDataInfo.setValue(name);
            requestDataInfo.setType("log");

            RequestLogInfo requestLogInfo = new RequestLogInfo();
            requestLogInfo.setPointer(Long.valueOf(pointer));
            requestLogInfo.setRows(5);
            requestDataInfo.setParams(requestLogInfo);

            //获取实例日志
            ReturnT returnT = JobRemotingUtil.postBody(url, requestDataInfo, 300);

            if (returnT != null && returnT.getCode() == 200) {
                if (returnT.getContent() != null) {
                    String toJsonString = JacksonUtil.toJsonString(returnT.getContent());
                    RequestLogInfo resultLogInfo = JacksonUtil.jsonStringToBean(toJsonString, RequestLogInfo.class);
                    return resultLogInfo;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }
}
